package com.tbl.modules.wms.controller.inventory;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.tbl.common.utils.DateUtils;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.modules.platform.constant.MenuConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.platform.util.DeriveExcel;
import com.tbl.modules.wms.entity.inventory.Inventory;
import com.tbl.modules.wms.service.inventory.InventoryRegistrationService;
import com.tbl.modules.wms.service.inventory.InventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 盘点登记
 * @author 70486
 */
@Controller
@RequestMapping(value = "/inventoryRegistration")
public class InventoryRegistrationController extends AbstractController {

    /**
     * 盘点登记服务类
     */
    @Autowired
    private InventoryRegistrationService inventoryRegistrationService;
    /**
     * 盘点任务服务类
     */
    @Autowired
    private InventoryService inventoryService;
    /**
     * 角色接口
     */
    @Autowired
    private RoleService roleService;

    /**
     * 跳转到盘点登记页面
     * @return ModelAndView
     */
    @RequestMapping(value = "/toList")
    public ModelAndView toList() {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("operationCode", roleService.selectOperationByRoleId(getSessionUser().getRoleId(), MenuConstant.inventoryRegistration));
        mv.setViewName("techbloom/stock/inventoryRegistration/inventoryRegistration_list");
        return mv;
    }

    /**
     * 跳转查看记录页面
     * @param id 盘点计划主键
     * @return ModelAndView
     */
    @RequestMapping("/infoView.do")
    public ModelAndView infoView(Long id) {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom/stock/inventoryRegistration/edit_view2");
        mv.addObject("id", id);
        mv.addObject("planId", inventoryService.selectById(id).getCode());
        return mv;
    }

    /**
     * 跳转查看差异页面
     * @param ids 盘点计划主键
     * @return ModelAndView
     */
    @RequestMapping("/resultView.do")
    public ModelAndView resultView(String[] ids) {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom/stock/inventoryRegistration/result_view");
        StringBuffer idsBuff = new StringBuffer();
        Arrays.asList(ids).forEach(s -> idsBuff.append(s).append(","));
        StringBuffer planIds = new StringBuffer();
        inventoryService.selectBatchIds(Arrays.stream(ids).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()))
                .forEach(inventory -> planIds.append(inventory.getCode()).append(","));
        mv.addObject("ids", idsBuff.toString().substring(0,idsBuff.length()-1));
        mv.addObject("planIds", planIds.toString().substring(0,planIds.length()-1));
        return mv;
    }

    /**
     * 查看：获得盘点任务详细信息
     * @param id 盘点任务编码
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/detailList.do")
    @ResponseBody
    public Map<String, Object> detailList(Long id) {
        Map<String, Object> map = new HashMap<>(3);
        PageTbl page = this.getPage();
        String sortName = page.getSortname();
        if (StringUtils.isEmpty(sortName)) {
            sortName = "";
            page.setSortname(sortName);
        }
        String sortOrder = page.getSortorder();
        if (StringUtils.isEmpty(sortOrder)) {
            sortOrder = "desc";
            page.setSortorder(sortOrder);
        }
        map.put("plan_id", id);
        map.put("order", page.getSortorder());
        PageUtils pageRegDetail = inventoryRegistrationService.getList(map);
        page.setTotalRows(pageRegDetail.getTotalCount() == 0 ? 1 : pageRegDetail.getTotalCount());
        map.put("rows", pageRegDetail.getList());
        executePageMap(map, page);
        return map;
    }

    /**
     * 审核：获得盘点结果详细信息
     * @param wmsCode WMS盘点单号
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/resultList.do")
    @ResponseBody
    public Map<String, Object> resultList(String wmsCode) {
        Map<String, Object> map = new HashMap<>(5);
        PageTbl page = this.getPage();
        //厂区
        StringBuffer buffer = new StringBuffer();
        //盘点表主键
        StringBuffer buffer1 = new StringBuffer();
        inventoryService.selectList(new EntityWrapper<Inventory>().in("CODE",wmsCode)).forEach(inventory -> {
            buffer.append(inventory.getFactorycode()).append(",");
            buffer1.append(inventory.getId()).append(",");
        });
        //盘的仓库主键
        map.put("warehouseIds", Arrays.asList(buffer.toString().split(",")));
        map.put("wmsCodePlanId", Arrays.asList(buffer1.toString().split(",")));
        map.put("queryString", request.getParameter("queryJsonString"));
        map.put("inventoryStateOther",request.getParameter("inventoryState"));
        map.put("inventoryState", com.tbl.common.utils.StringUtils.isNotBlank(request.getParameter("inventoryState"))?
               Arrays.asList(request.getParameter("inventoryState").split(",")):null);
        PageUtils pageResultDetail = inventoryRegistrationService.getContrastList(page, map);
        page.setTotalRows(pageResultDetail.getTotalCount() == 0 ? 1 : pageResultDetail.getTotalCount());
        executePageMap(map, page);
        map.put("total", pageResultDetail.getTotalPage() == 0 ? 1 : pageResultDetail.getTotalPage());
        map.put("rows", pageResultDetail.getList());
        return map;
    }

    /**
     * 导出盘点登记查看明细Excel
     * @param request
     * @param response
     */
    @RequestMapping(value = "/detailExcel.do", method = RequestMethod.POST)
    @ResponseBody
    public void detailExcel(HttpServletRequest request, HttpServletResponse response)  {
        try {
            String sheetName = "盘库清单" + "(" + DateUtils.getDay() + ")";
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("gbk"),
                    "ISO8859-1") + ".xls");

            Map<String, String> mapFields = new LinkedHashMap<>();
            mapFields.put("qaCode", "质保单号");
            mapFields.put("batchNo", "批次号");
            mapFields.put("outerDiameter", "盘外径");
            mapFields.put("innerDiameter", "盘内径");
            mapFields.put("model", "盘规格");
            mapFields.put("dishcode", "盘号");
            mapFields.put("materialCode", "物料编码");
            mapFields.put("materialName", "物料名称");
            mapFields.put("meter", "库存米数");
            mapFields.put("inventoryMeter", "盘点米数");
            mapFields.put("shelfCode", "库存库位");
            mapFields.put("inventoryShelf", "盘点库位");
            mapFields.put("inventoryName", "盘点人");
            mapFields.put("uploadTimeStr", "盘点时间");
            mapFields.put("result", "结果");
            DeriveExcel.exportExcel(sheetName, inventoryRegistrationService.selectInventoryDifference(
                    com.tbl.common.utils.StringUtils.stringToList(request.getParameter("ids")),
                    request.getParameter("infoid")), mapFields, response, "");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
